"""
@author: Zhang Wenzhou
@file: userinfo.py
@time: 2023/3/4 0004 15:18:28
"""
from flask import Blueprint, request
from flask_restful import Resource, Api
from model.userdb.userinfo import User
from model.user import StuInfo
from model import db
from libs.response import response_data
from libs.auth import login, create_token
from forms.user import UserForm, LoginForm
from libs.handler import default_error_handler
from libs.send_user_mail import send_mail
from celery_app.tasks import celery_task

userapi_bp = Blueprint("userapi_bp", __name__, url_prefix="/v1")
api = Api(userapi_bp)

# 测试环境注释掉，不好排错
# api.handle_error = default_error_handler

class UserView(Resource):
    def post(self):
        try:
            data = request.json
            form = UserForm(data=data)
            if form.validate():
                User.create_user(username=data.get("username"),
                                 password=form.password.data,
                                 email=data.get("email")
                                 )
                celery_task.delay(data.get("email"), data.get("username"))

                return response_data(message="注册成功")
            else:
                return response_data(code=1, message=form.errors)
        except:
            return response_data(code=1, message="注册失败,出错啦~")

    def put(self):
        # 调用异步任务

        # 发送任务
        celery_task.delay("this is put method")
        return "this is put"

api.add_resource(UserView, "/user")

class LoginView(Resource):
    @login
    def post(self):
        try:
            data = request.json
            form = LoginForm(data=data)
            user = form.validate()
            if user:
                # 验证通过，生成token
                token = create_token(user.id)
                return response_data(message="login success", data={"token": token,
                                                                    "username": user.username})
            else:
                return response_data(message=form.errors)
        except:
            return response_data(code=1, message="登录失败")

    @login
    def get(self):
        return response_data(message="get users")

api.add_resource(LoginView, "/login")

"""
token验证
1、服务器登录验证成功，返回token
    token 基于JWS规范返回
2、前端发起登录请求保存token -- 保存在浏览器本地存储
"""
